var msgNoticeConfigTable = function () {
    var tableId = "msgNoticeConfigTable";
    return {
        init: function () {
            msgNoticeConfigTable._initTable();
            msgNoticeConfigTable._query();
            msgNoticeConfigTable._reset();
            msgNoticeConfigTable._keyQuery();
            msgNoticeConfigTable._edit();
            msgNoticeConfigTable._save();
            msgNoticeConfigTable._changeReceiveTime();
            msgNoticeConfigTable._initDateControl();
            msgNoticeConfigTable._modalHidden();
            msgNoticeConfigTable._receiverTypeChange();
            msgNoticeConfigTable._noticeAlertTypeChange();
        },
        _initTable: function () {
            util.initCheckBox(tableId);

            //查询字典信息列表
            function queryData(sSource, aoData, fnCallback) {
                aoData.push({
                    "name": "truename",
                    "value": $("#name").val().trim()
                });
                $.ajax({
                    "type": "post",
                    "url": sSource,
                    "dataType": "json",
                    "data": {
                        "aoData": JSON.stringify(aoData)
                    },
                    "success": function (resp) {
                        fnCallback(resp);
                    }
                });
            }

            $('#msgNoticeConfigTable').DataTable({
                "processing": true,
                "serverSide": true,
                "sAjaxSource": "main/msg/notice/getNoticeConfig.mvc",
                "fnServerData": queryData,
                "pageLength": 10,
                "sDom": "<'row-fluid'r>t<'row-fluid'<'span6'i><'span6'p>>",
                "oLanguage": util.getDToLanguage(),
                "columns": [
                    {
                        "data": "receiver",
                        "render": function () {
                            return '<div class="checker" onclick="util.selectCheckBox(\'' + tableId + '\',this)"><span><input type="checkbox" class="checkboxes"/></span></div>';
                        },
                        "bSortable": false
                    },
                    {
                        "data": "truename",
                        "bSortable": false,
                        "sWidth": "150px",
                        "defaultContent": ""
                    },
                    {
                        "data": "showMessage",
                        "bSortable": false,
                        "render": function (data) {
                            if ("1" === data) {
                                return "√"
                            }
                            return ""
                        },
                        "sWidth": "80px",
                        "defaultContent": ""

                    },
                    {
                        "data": "sendSmsFlag",
                        "bSortable": false,
                        "render": function (data) {
                            if ("1" === data) {
                                return "√"
                            }
                            return ""
                        },
                        "sWidth": "80px",
                        "defaultContent": ""
                    },
                    {
                        "data": "sendEmailFlag",
                        "bSortable": false,
                        "render": function (data) {
                            if ("1" === data) {
                                return "√"
                            }
                            return ""
                        },
                        "sWidth": "80px",
                        "defaultContent": ""
                    },
                    {
                        "data": "alertDefinitions",
                        "bSortable": false,
                        "render": function (data) {
                            var alertType = "";
                            for (var i = 0; i < data.length; i++) {
                                alertType += data[i].alertCode+data[i].alertName + ";"
                            }
                            return alertType.length > 0 ? alertType.substring(0, alertType.length - 1) : "";
                        },
                        "defaultContent": ""

                    },
                    {
                        "data": "noticeTimes",
                        "bSortable": false,
                        "render": function (data, type, full, meta) {
                            if(full.noticeTimeType === '1') {
                                return "7*24小时"
                            }
                            //debugger
                            var noticeTime = "";
                            for (var i = 0; i < data.length; i++) {
                                noticeTime += "周" + msgNoticeConfigTable._convertWeek(data[i].week) + "" + data[i].startTime + "-" + data[i].endTime + ";";
                            }
                            return noticeTime.length > 0 ? noticeTime.substring(0, noticeTime.length - 1) : "";
                        },
                        "defaultContent": ""
                    }
                ],
                "fnDrawCallback": function () {
                    util.clearSelected(tableId);
                }
            });
        },
        _query: function () {
            $("#queryMsgNoticeConfigButton").on("click",function () {
                var table = $('#msgNoticeConfigTable').DataTable();
                table.draw(true);
            })
        },
        _reset:function () {
            $(".reset").on("click",function () {
                $("#truename").val('');
            })
        },
        _keyQuery:function () {
            $(".search-input").off("click").keypress(function (event) {
                event.preventDefault();
                if (event.keyCode === 13) {
                    //回车执行查询
                    $("#queryMsgNoticeConfigButton").click();
                }
            })
        },
        _edit: function () {
            $("#msgNoticeConfigEdit").on("click",function () {
                var d = util.getCheckedData("msgNoticeConfigTable");
                if (d.length !== 1) {
                    util.showModal("#_alertModal", "请选择一条记录进行操作！");
                    return false;
                }
                $.ajax({
                    "type" : "post",
                    "url" : "main/msg/notice/getMsgNoticeConfig.mvc",
                    "dataType" : "json",
                    "async":false,
                    "data" : {
                        receiver:d[0].receiver
                    },
                    "success" : function(response) {
                        if (response.result) {
                            var _data = response.data;
                            if (_data.showMessage === '1') {
                                $("#msgNoticeConfigModal").find("input:checkbox[name='showMessage']").parent().addClass("checked");
                                $("#msgNoticeConfigModal").find("input:checkbox[name='showMessage']").prop("checked",true);
                            }
                            if (_data.sendSmsFlag === '1') {
                                $("#msgNoticeConfigModal").find("input:checkbox[name='sendSmsFlag']").parent().addClass("checked");
                                $("#msgNoticeConfigModal").find("input:checkbox[name='sendSmsFlag']").prop("checked",true);
                            }
                            if (_data.sendEmailFlag === '1') {
                                $("#msgNoticeConfigModal").find("input:checkbox[name='sendEmailFlag']").parent().addClass("checked");
                                $("#msgNoticeConfigModal").find("input:checkbox[name='sendEmailFlag']").prop("checked",true);
                            }
                            if((!$("#msgNoticeConfigModal").find("input:checkbox[name='showMessage']").is(":checked"))
                                &&(!$("#msgNoticeConfigModal").find("input:checkbox[name='sendSmsFlag']").is(":checked"))
                                &&(!$("#msgNoticeConfigModal").find("input:checkbox[name='sendEmailFlag']").is(":checked"))
                            ) {
                                $("#msgNoticeConfigModal").find("input:checkbox[name='alertCode']").attr("disabled","disabled");
                            } else {
                                $("#msgNoticeConfigModal").find("input:checkbox[name='alertCode']").removeAttr("disabled");
                            }
                            for (var i=0;i<_data.alertDefinitions.length;i++) {
                                $("#msgNoticeConfigModal").find("input:checkbox[value='"+_data.alertDefinitions[i].alertCode+"']").parent().addClass("checked");
                                $("#msgNoticeConfigModal").find("input:checkbox[value='"+_data.alertDefinitions[i].alertCode+"']").prop("checked",true);
                            }
                            if ( _data.noticeTimeType) {
                                $("#msgNoticeConfigModal").find("input:radio[value='"+_data.noticeTimeType+"']").attr("checked","checked");
                                $("#msgNoticeConfigModal").find("input:radio[value='"+_data.noticeTimeType+"']").trigger("click");
                            } else {
                                $("#msgNoticeConfigModal").find("input:radio[value='1']").attr("checked","checked");
                                $("#msgNoticeConfigModal").find("input:radio[value='1']").trigger("click");
                            }
                            if (_data.noticeTimeType === '1'||(!_data.noticeTimeType)) {
                                $("#msgNoticeConfigModal").find("input.start-time").val("09:00");
                                $("#msgNoticeConfigModal").find("input.end-time").val("18:00");
                            }
                            if (_data.noticeTimeType === '2') {
                                for (var j=0;j<_data.noticeTimes.length;j++) {
                                    $("#weekday").find("li."+msgNoticeConfigTable._convertWeekEn(_data.noticeTimes[j].week)).find("input.start-time").val(_data.noticeTimes[j].startTime);
                                    $("#weekday").find("li."+msgNoticeConfigTable._convertWeekEn(_data.noticeTimes[j].week)).find("input.end-time").val(_data.noticeTimes[j].endTime);
                                }
                            }
                            if (_data.noticeTimeType === '3') {
                                for (var k=0;k<_data.noticeTimes.length;k++) {
                                    $("#weekend").find("li."+msgNoticeConfigTable._convertWeekEn(_data.noticeTimes[k].week)).find("input.start-time").val(_data.noticeTimes[k].startTime);
                                    $("#weekend").find("li."+msgNoticeConfigTable._convertWeekEn(_data.noticeTimes[k].week)).find("input.end-time").val(_data.noticeTimes[k].endTime);
                                }
                            }
                            if (_data.noticeTimeType === '4') {
                                for (var m=0;m<_data.noticeTimes.length;m++) {
                                    $("#custom").find("li."+msgNoticeConfigTable._convertWeekEn(_data.noticeTimes[m].week)).find("input.start-time").val(_data.noticeTimes[m].startTime);
                                    $("#custom").find("li."+msgNoticeConfigTable._convertWeekEn(_data.noticeTimes[m].week)).find("input.end-time").val(_data.noticeTimes[m].endTime);
                                }
                            }
                            if ((!_data.noticeTimes)||_data.noticeTimes.length ===0) {
                                $("#msgNoticeConfigModal").find("input.start-time").val("09:00");
                                $("#msgNoticeConfigModal").find("input.end-time").val("18:00");
                            }

                            /*if ((!_data.alertDefinitions)||_data.alertDefinitions.length ===0) {
                                $("#msgNoticeConfigModal").find("input:checkbox[name='alertCode']").parent().addClass("checked");
                                $("#msgNoticeConfigModal").find("input:checkbox[name='alertCode']").prop("checked",true);
                            }*/

                            $("#msgNoticeConfigModal").find("input[name='receiver']").val(d[0].receiver);
                            $("#msgNoticeConfigModal").modal({show:true,keyboard:false});

                        } else {
                            rmsBox.notify('error', {msg: '系统异常！',delay:3000});
                        }

                    }
                });

            })
        },
        _save:function () {
            $("#msgNoticeConfigSave").on("click",function (e) {
                e.preventDefault();
                var entity = {};
                var alertDefinitions = [];
                if($("#msgNoticeConfigModal").find("input:checkbox[name='showMessage']").is(":checked")) {
                    entity['showMessage'] = '1'
                } else {
                    entity['showMessage'] = '0'
                }
                if($("#msgNoticeConfigModal").find("input:checkbox[name='sendSmsFlag']").is(":checked")) {
                    entity['sendSmsFlag'] = '1'
                } else {
                    entity['sendSmsFlag'] = '0'
                }
                if($("#msgNoticeConfigModal").find("input:checkbox[name='sendEmailFlag']").is(":checked")) {
                    entity['sendEmailFlag'] = '1'
                } else {
                    entity['sendEmailFlag'] = '0'
                }
                $("#noticeAlertType").find("input:checkbox[name='alertCode']:checked").each(function() {
                    alertDefinitions.push({
                        alertCode:$(this).val()
                    });
                });
                entity['alertDefinitions'] = alertDefinitions;
                var noticeTimes = [];
                var noticeType = $("#msgNoticeConfigModal").find("input:radio[name='noticeTime']:checked").val();
                console.log(noticeType);
                entity['noticeTimeType'] = noticeType;
                //7*24小时
                if (noticeType === '1') {
                    for (var i=1;i<=7;i++) {
                        noticeTimes.push({
                            week:''+i,
                            startTime:'00:00',
                            endTime:'23:59'
                        })
                    }
                } else if (noticeType === '2') {
                //工作日
                    //周一
                    noticeTimes.push({
                        week:'1',
                        startTime:$("#weekday").find("li.monday").find("input.start-time").val(),
                        endTime:$("#weekday").find("li.monday").find("input.end-time").val()
                    });
                    //周二
                    noticeTimes.push({
                        week:'2',
                        startTime:$("#weekday").find("li.tuesday").find("input.start-time").val(),
                        endTime:$("#weekday").find("li.tuesday").find("input.end-time").val()
                    });
                    //周三
                    noticeTimes.push({
                        week:'3',
                        startTime:$("#weekday").find("li.wednesday").find("input.start-time").val(),
                        endTime:$("#weekday").find("li.wednesday").find("input.end-time").val()
                    });
                    //周四
                    noticeTimes.push({
                        week:'4',
                        startTime:$("#weekday").find("li.thursday").find("input.start-time").val(),
                        endTime:$("#weekday").find("li.thursday").find("input.end-time").val()
                    });
                    //周五
                    noticeTimes.push({
                        week:'5',
                        startTime:$("#weekday").find("li.friday").find("input.start-time").val(),
                        endTime:$("#weekday").find("li.friday").find("input.end-time").val()
                    });
                } else if (noticeType === '3') {
                    //周六
                    noticeTimes.push({
                        week:'6',
                        startTime:$("#weekend").find("li.saturday").find("input.start-time").val(),
                        endTime:$("#weekend").find("li.saturday").find("input.end-time").val()
                    });
                    //周日
                    noticeTimes.push({
                        week:'7',
                        startTime:$("#weekend").find("li.sunday").find("input.start-time").val(),
                        endTime:$("#weekend").find("li.sunday").find("input.end-time").val()
                    });
                } else if (noticeType === '4') {
                    //周一
                    noticeTimes.push({
                        week:'1',
                        startTime:$("#custom").find("li.monday").find("input.start-time").val(),
                        endTime:$("#custom").find("li.monday").find("input.end-time").val()
                    });
                    //周二
                    noticeTimes.push({
                        week:'2',
                        startTime:$("#custom").find("li.tuesday").find("input.start-time").val(),
                        endTime:$("#custom").find("li.tuesday").find("input.end-time").val()
                    });
                    //周三
                    noticeTimes.push({
                        week:'3',
                        startTime:$("#custom").find("li.wednesday").find("input.start-time").val(),
                        endTime:$("#custom").find("li.wednesday").find("input.end-time").val()
                    });
                    //周四
                    noticeTimes.push({
                        week:'4',
                        startTime:$("#custom").find("li.thursday").find("input.start-time").val(),
                        endTime:$("#custom").find("li.thursday").find("input.end-time").val()
                    });
                    //周五
                    noticeTimes.push({
                        week:'5',
                        startTime:$("#custom").find("li.friday").find("input.start-time").val(),
                        endTime:$("#custom").find("li.friday").find("input.end-time").val()
                    });
                    //周六
                    noticeTimes.push({
                        week:'6',
                        startTime:$("#custom").find("li.saturday").find("input.start-time").val(),
                        endTime:$("#custom").find("li.saturday").find("input.end-time").val()
                    });
                    //周日
                    noticeTimes.push({
                        week:'7',
                        startTime:$("#custom").find("li.sunday").find("input.start-time").val(),
                        endTime:$("#custom").find("li.sunday").find("input.end-time").val()
                    });
                }
                entity['noticeTimes'] = noticeTimes;
                //选了通知方式，未选告警类型
                if ((entity['showMessage'] === '1'||entity['sendSmsFlag'] === '1'||entity['sendEmailFlag'] === '1')&&alertDefinitions.length===0) {
                    $("#infoBox").show().text("提示信息：请选择接收告警类型！");
                    return
                }
                //接收方式和告警类型都没选 通知时间清空
                if (entity['showMessage'] === '0'&&entity['sendSmsFlag'] === '0'&&entity['sendEmailFlag'] === '0'&&alertDefinitions.length===0) {
                    entity['noticeTimes'] = [];
                }
                entity['receiver'] = $("#msgNoticeConfigModal").find("input[name='receiver']").val();
                console.log(entity);
                var table = $('#msgNoticeConfigTable').DataTable();
                var currentPage =table.page();
                $.ajax({
                    "type" : "post",
                    "url" : "main/msg/notice/saveMsgNoticeConfig.mvc",
                    "dataType" : "json",
                    "async":false,
                    "contentType": "application/json; charset=utf-8",
                    "data" : JSON.stringify(entity),
                    "success" : function(response) {
                        if(response.result){
                            rmsBox.notify('success', {msg: '保存成功！'});
                            $("#form_btn_close").click();
                            table.page(currentPage).draw('page');
                        }else{
                            rmsBox.notify('error', {msg: '保存失败！',delay:3000});
                        }

                    }
                });

            })
        },
        _convertWeek: function (week) {
            var int = parseInt(week);
            var weekArr = ["一", "二", "三", "四", "五", "六", "日"];
            if (int > 0 && int <= 7) {
                return weekArr[int - 1];
            }
            return "";
        },
        _convertWeekEn: function (week) {
            var int = parseInt(week);
            var weekArr = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"];
            if (int > 0 && int <= 7) {
                return weekArr[int - 1];
            }
            return "";
        },
        _changeReceiveTime : function () {
            $('.tab-item > li').on('click',function() {
                var index = $(this).index();
                $('.date-frame > li').eq(index).addClass('active').siblings().removeClass('active');

            })
        },
        _initDateControl : function () {
            $(".form-date-hour").on('click',WdatePicker({dateFmt:'HH:mm'}))
        },
        _modalHidden : function () {
            $("#form_btn_close").on('click',function (e) {
                e.preventDefault();
                $("#msgNoticeConfigModal").find("input.start-time").val("09:00");
                $("#msgNoticeConfigModal").find("input.end-time").val("18:00");
                $("#msgNoticeConfigModal").find("input:radio[value='1']").attr("checked","checked");
                $("#msgNoticeConfigModal").find("input:radio[value='1']").trigger("click");
                $("#msgNoticeConfigModal").find("input:checkbox").prop("checked",false);
                $("#msgNoticeConfigModal").find("input:checkbox").each(function () {
                    $(this).parent().removeClass("checked");
                })

            })
        },
        _receiverTypeChange:function () {
            $("#receiveType").find("input:checkbox").on("click",function () {
                if((!$("#msgNoticeConfigModal").find("input:checkbox[name='showMessage']").is(":checked"))
                    &&(!$("#msgNoticeConfigModal").find("input:checkbox[name='sendSmsFlag']").is(":checked"))
                    &&(!$("#msgNoticeConfigModal").find("input:checkbox[name='sendEmailFlag']").is(":checked"))
                ) {
                    $("#msgNoticeConfigModal").find("input:checkbox[name='alertCode']").prop("checked",false).parent().removeClass("checked");
                    $("#msgNoticeConfigModal").find("input:checkbox[name='alertCode']").attr("disabled","disabled");
                } else {
                    $("#msgNoticeConfigModal").find("input:checkbox[name='alertCode']").removeAttr("disabled");
                }
            })
        },
        _noticeAlertTypeChange:function () {
            $("#noticeAlertType").find("input:checkbox").on("click",function () {
                $("#infoBox").hide();
            })
        }

    }
}();